# FFmpeg Android编译脚本 (Windows PowerShell版本)
# 使用方法: .\build_ffmpeg_android_windows.ps1

param(
    [string]$AndroidNdkRoot = "",
    [string]$BuildDir = ".\ffmpeg_build",
    [string]$OutputDir = ".\android\app\src\main\jniLibs"
)

# 检查NDK路径
if ([string]::IsNullOrEmpty($AndroidNdkRoot)) {
    # 尝试自动查找NDK
    $possiblePaths = @(
        "$env:ANDROID_HOME\ndk-bundle",
        "$env:ANDROID_HOME\ndk\25.1.8937393",
        "$env:LOCALAPPDATA\Android\Sdk\ndk\25.1.8937393",
        "C:\Android\Sdk\ndk\25.1.8937393"
    )
    
    foreach ($path in $possiblePaths) {
        if (Test-Path $path) {
            $AndroidNdkRoot = $path
            break
        }
    }
    
    if ([string]::IsNullOrEmpty($AndroidNdkRoot)) {
        Write-Host "❌ 错误: 未找到Android NDK" -ForegroundColor Red
        Write-Host "请设置Android NDK路径:" -ForegroundColor Yellow
        Write-Host "  .\build_ffmpeg_android_windows.ps1 -AndroidNdkRoot 'C:\path\to\android-ndk'" -ForegroundColor Yellow
        exit 1
    }
}

Write-Host "🔍 使用Android NDK路径: $AndroidNdkRoot" -ForegroundColor Green

# 检查NDK是否存在
if (-not (Test-Path $AndroidNdkRoot)) {
    Write-Host "❌ 错误: Android NDK路径不存在: $AndroidNdkRoot" -ForegroundColor Red
    exit 1
}

# 检查必需的工具
$requiredTools = @("wget", "tar", "make")
$missingTools = @()

foreach ($tool in $requiredTools) {
    if (-not (Get-Command $tool -ErrorAction SilentlyContinue)) {
        $missingTools += $tool
    }
}

if ($missingTools.Count -gt 0) {
    Write-Host "❌ 错误: 缺少必需的工具: $($missingTools -join ', ')" -ForegroundColor Red
    Write-Host "请安装以下工具:" -ForegroundColor Yellow
    Write-Host "  - Git Bash (包含wget, tar, make)" -ForegroundColor Yellow
    Write-Host "  - 或使用WSL (Windows Subsystem for Linux)" -ForegroundColor Yellow
    exit 1
}

Write-Host "✅ 环境检查通过" -ForegroundColor Green

# 创建构建目录
Write-Host "📁 创建构建目录..." -ForegroundColor Blue
New-Item -ItemType Directory -Path $BuildDir -Force | Out-Null
Set-Location $BuildDir

# 下载FFmpeg源码
$FFmpegVersion = "6.0"
$FFmpegDir = "ffmpeg-$FFmpegVersion"

if (-not (Test-Path $FFmpegDir)) {
    Write-Host "📥 下载FFmpeg源码..." -ForegroundColor Blue
    $FFmpegUrl = "https://ffmpeg.org/releases/ffmpeg-$FFmpegVersion.tar.bz2"
    $FFmpegArchive = "ffmpeg-$FFmpegVersion.tar.bz2"
    
    try {
        Invoke-WebRequest -Uri $FFmpegUrl -OutFile $FFmpegArchive
        Write-Host "✅ 下载完成" -ForegroundColor Green
    } catch {
        Write-Host "❌ 下载失败: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
    
    Write-Host "📦 解压源码..." -ForegroundColor Blue
    try {
        # 使用tar解压
        tar -xjf $FFmpegArchive
        Write-Host "✅ 解压完成" -ForegroundColor Green
    } catch {
        Write-Host "❌ 解压失败: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

Set-Location $FFmpegDir

# 设置环境变量
$env:ANDROID_NDK_ROOT = $AndroidNdkRoot
$env:PATH = "$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin;$env:PATH"

Write-Host "🔧 开始编译FFmpeg..." -ForegroundColor Blue

# 编译函数
function Build-FFmpeg {
    param(
        [string]$Arch,
        [string]$Cpu,
        [string]$Prefix,
        [string]$CrossPrefix
    )
    
    Write-Host "📱 编译 $Arch 架构..." -ForegroundColor Yellow
    
    $configureArgs = @(
        "--prefix=$Prefix",
        "--target-os=android",
        "--arch=$Arch",
        "--cpu=$Cpu",
        "--enable-cross-compile",
        "--cross-prefix=$CrossPrefix",
        "--sysroot=$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\sysroot",
        "--enable-shared",
        "--disable-static",
        "--enable-gpl",
        "--enable-version3",
        "--disable-doc",
        "--disable-programs",
        "--disable-ffmpeg",
        "--disable-ffplay",
        "--disable-ffprobe",
        "--disable-avdevice",
        "--disable-avfilter",
        "--disable-postproc",
        "--disable-encoders",
        "--disable-decoders",
        "--enable-decoder=h264",
        "--enable-decoder=h265",
        "--enable-decoder=vp8",
        "--enable-decoder=vp9",
        "--enable-decoder=aac",
        "--enable-decoder=mp3",
        "--enable-decoder=opus",
        "--enable-decoder=vorbis",
        "--enable-decoder=flac",
        "--enable-decoder=wav",
        "--enable-decoder=pcm",
        "--disable-network",
        "--disable-protocols",
        "--disable-filters",
        "--disable-hwaccels",
        "--disable-parsers",
        "--disable-bsfs",
        "--disable-indevs",
        "--disable-outdevs",
        "--disable-devices",
        "--disable-debug",
        "--disable-ffplay",
        "--disable-ffprobe",
        "--disable-doc",
        "--disable-manpages",
        "--disable-podpages",
        "--disable-txtpages",
        "--disable-htmlpages"
    )
    
    try {
        # 配置
        & .\configure @configureArgs
        if ($LASTEXITCODE -ne 0) {
            throw "配置失败"
        }
        
        # 清理
        & make clean
        if ($LASTEXITCODE -ne 0) {
            throw "清理失败"
        }
        
        # 编译
        & make -j4
        if ($LASTEXITCODE -ne 0) {
            throw "编译失败"
        }
        
        # 安装
        & make install
        if ($LASTEXITCODE -ne 0) {
            throw "安装失败"
        }
        
        Write-Host "✅ $Arch 架构编译完成" -ForegroundColor Green
    } catch {
        Write-Host "❌ $Arch 架构编译失败: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

# 编译不同架构
$architectures = @(
    @{Arch="aarch64"; Cpu="armv8-a"; Prefix="$BuildDir\android\arm64-v8a"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\aarch64-linux-android21-"},
    @{Arch="arm"; Cpu="armv7-a"; Prefix="$BuildDir\android\armeabi-v7a"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\armv7a-linux-androideabi21-"},
    @{Arch="x86_64"; Cpu="x86_64"; Prefix="$BuildDir\android\x86_64"; CrossPrefix="$AndroidNdkRoot\toolchains\llvm\prebuilt\windows-x86_64\bin\x86_64-linux-android21-"}
)

foreach ($arch in $architectures) {
    Build-FFmpeg -Arch $arch.Arch -Cpu $arch.Cpu -Prefix $arch.Prefix -CrossPrefix $arch.CrossPrefix
}

# 复制库文件到项目目录
Write-Host "📋 复制库文件到项目目录..." -ForegroundColor Blue

$outputArchs = @("arm64-v8a", "armeabi-v7a", "x86_64")
foreach ($arch in $outputArchs) {
    $sourceDir = "$BuildDir\android\$arch"
    $targetDir = "$OutputDir\$arch"
    
    New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
    
    if (Test-Path "$sourceDir\lib") {
        Copy-Item "$sourceDir\lib\*.so" $targetDir -Force
        Write-Host "✅ 复制 $arch 库文件" -ForegroundColor Green
    } else {
        Write-Host "⚠️  $arch 库文件未找到" -ForegroundColor Yellow
    }
}

# 复制头文件
$includeSource = "$BuildDir\android\arm64-v8a\include"
$includeTarget = "$OutputDir\include"

if (Test-Path $includeSource) {
    New-Item -ItemType Directory -Path $includeTarget -Force | Out-Null
    Copy-Item "$includeSource\*" $includeTarget -Recurse -Force
    Write-Host "✅ 复制头文件" -ForegroundColor Green
}

Write-Host ""
Write-Host "🎉 FFmpeg Android编译完成！" -ForegroundColor Green
Write-Host "📁 库文件位置: $OutputDir" -ForegroundColor Blue
Write-Host "📁 头文件位置: $OutputDir\include" -ForegroundColor Blue
Write-Host ""
Write-Host "🔧 下一步:" -ForegroundColor Yellow
Write-Host "  1. 检查库文件是否正确生成" -ForegroundColor White
Write-Host "  2. 运行项目测试编译" -ForegroundColor White
Write-Host "  3. 验证FFmpeg功能" -ForegroundColor White
